#include "login_module.h"
#include <iostream>
#include <regex>

namespace TakeAwayPlatform
{
    LoginModule::LoginModule(DatabaseHandler& dbHandler) : dbHandler(dbHandler) {}

    bool LoginModule::login(const std::string& phone, const std::string& password, User& user)
    {
        std::string sql = "SELECT user_id, phone, password, role_id, nickname FROM users WHERE phone = '" + phone + "' AND password = '" + password + "'";
        Json::Value result = dbHandler.query(sql);

        if (result.size() > 0)
        {
            user = User(result[0]["user_id"].asInt(), result[0]["phone"].asString(), result[0]["password"].asString(), static_cast<Role>(result[0]["role_id"].asInt()), result[0]["nickname"].asString());
            std::cout << "Login successful. Welcome, " << user.getNickname() << "!" << std::endl;
            return true;
        }
        else
        {
            std::cerr << "Login failed. Invalid phone or password." << std::endl;
            return false;
        }
    }

    bool LoginModule::registerUser(const std::string& phone, const std::string& password, const std::string& nickname)
    {
        std::string sql = "SELECT * FROM users WHERE phone = '" + phone + "'";
        Json::Value result = dbHandler.query(sql);

        if (result.size() > 0)
        {
            std::cerr << "Phone number already registered." << std::endl;
            return false;
        }

        sql = "INSERT INTO users (phone, password, role_id, nickname) VALUES ('" + phone + "', '" + password + "', 1, '" + nickname + "')";
        return dbHandler.update(sql);
    }

    bool LoginModule::changePassword(const std::string& phone, const std::string& oldPassword, const std::string& newPassword)
    {
        std::string sql = "UPDATE users SET password = '" + newPassword + "' WHERE phone = '" + phone + "' AND password = '" + oldPassword + "'";
        return dbHandler.update(sql);
    }

    bool LoginModule::changePhone(const std::string& oldPhone, const std::string& newPhone)
    {
        std::string sql = "UPDATE users SET phone = '" + newPhone + "' WHERE phone = '" + oldPhone + "'";
        return dbHandler.update(sql);
    }
}